package data

import (
	"context"
	"io"

	"github.com/minio/minio-go/v7"
)

const (
	ReviewBucketName = "review-image"
)

type ImageRepo struct {
	minio *minio.Client
}

func NewImageRepo(minioClient *minio.Client) *ImageRepo {
	// 现实开发中，不建议这么写，应该由DBA创建
	// 检查 bucket 是否存在，不存在则创建
	ctx := context.Background()
	err := minioClient.MakeBucket(ctx, ReviewBucketName, minio.MakeBucketOptions{Region: "us-east-1"})
	if err != nil {
		// Check to see if we already own this bucket (which happens if you run this twice)
		exists, errBucketExists := minioClient.BucketExists(ctx, ReviewBucketName)
		if !(errBucketExists == nil && exists) {
			panic(errBucketExists)
		}
	}

	return &ImageRepo{
		minio: minioClient,
	}
}
func (r *ImageRepo) UploadImage(ctx context.Context, f io.Reader, size int64, fileName string) error {
	contentType := "application/octet-stream"
	if _, err := r.minio.PutObject(ctx, ReviewBucketName, fileName, f, size, minio.PutObjectOptions{ContentType: contentType}); err != nil {
		return err
	}
	return nil
}
